// 图片压缩函数
export function compressImg(file) {
  let files;
  let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2);
  let read = new FileReader();
  read.readAsDataURL(file);
  return new Promise(function (resolve, reject) {
    read.onload = function (e) {
      let img = new Image();
      img.src = e.target.result;
      img.onload = function () {
        // 默认按比例压缩
        let w = this.width;
        let h = this.height;
        //等比例裁剪
        let originHeight = this.height;
        let originWidth = this.width;
        const MAX_WIDTH = 1600;
        const MAX_HEIGHT = 1600;
        w = originWidth;
        h = originHeight;
        if (originWidth > MAX_WIDTH || originHeight > MAX_HEIGHT) {
          if (originWidth / originHeight > MAX_WIDTH / MAX_HEIGHT) {
            // 更宽，按照宽度限定尺寸
            w = MAX_WIDTH;
            h = Math.round(MAX_WIDTH * (originHeight / originWidth));
          } else {
            h = MAX_HEIGHT;
            w = Math.round(MAX_HEIGHT * (originWidth / originHeight));
          }
        }
        // 生成canvas
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        let base64;
        // 创建属性节点
        canvas.setAttribute('width', w);
        canvas.setAttribute('height', h);
        ctx.drawImage(this, 0, 0, w, h);
        const fileType = file['type'] === 'image/png' ? 'image/jpeg' : file['type'];
        if (fileSize < 1) {
          // 如果图片小于一兆 那么压缩0.5
          base64 = canvas.toDataURL(fileType, 0.5);
        } else if (fileSize > 1 && fileSize < 2) {
          // 如果图片大于1M并且小于2M 那么压缩0.5
          base64 = canvas.toDataURL(fileType, 0.5);
        } else {
          // 如果图片超过2m 那么压缩0.2
          base64 = canvas.toDataURL(fileType, 0.2);
        }
        // 回调函数返回file的值（将base64编码转成file）
        files = dataURLtoFile(base64, file.name);
        resolve(files);
      };
    };
  });
}

// base64转码（压缩完成后的图片为base64编码，这个方法可以将base64编码转回file文件）
function dataURLtoFile(dataurl, filename) {
  let arr = dataurl.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
